<template>
	<div class="icon-select-container relative">
		<el-popover placement="bottom-start" v-model:visible="visible" :teleported="false" :width="width"
			trigger="click">
			<template #reference>
				<el-button :icon="selectValue">
					<span class="ml-4px">{{ selectValue || '点击选择图标' }}</span>
				</el-button>
			</template>
			<el-input v-model="searchValue" placeholder="输入名称搜索图标" />
			<el-divider border-style="dashed" style="margin: 10px 0;" />
			<el-scrollbar :height="scrollbarHeight">
				<div class="icon-list">
					<template v-for="icon in elementIcons" :key="icon">
						<div class="icon-item click" @click="selectIcon(icon)">
							<el-icon size="24">
								<component :is="icon"></component>
							</el-icon>
						</div>
					</template>
				</div>
			</el-scrollbar>
		</el-popover>
	</div>
</template>

<script>
	import * as ElementPlusIconsVue from '@element-plus/icons-vue'
	export default {
		name: 'iconSelect',
		props: {
			type: {
				type: String,
				default: 'input'
			},
			width: {
				type: Number,
				default: 300
			},
			scrollbarHeight: {
				type: Number,
				default: 200
			},
			defaultValue: {
				type: String,
				default:''
			}
		},
		watch: {
			searchValue(a, b) {
				this.elementIcons = JSON.parse(JSON.stringify(this.elementIconsDefault))
				if (a == '') {
					return
				}
				this.elementIcons = this.elementIcons.filter((item, index) => {
					return item.toLowerCase().indexOf(a.toLowerCase()) !== -1
				})
			}
		},
		data() {
			return {
				visible: false,
				elementIcons: [],
				elementIconsDefault: [],
				searchValue: '',
				selectValue: '',
			}
		},
		created() {
			for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
				this.elementIcons.push(key)
				this.elementIconsDefault.push(key)
			}
			this.selectValue = this.defaultValue
		},
		methods: {
			selectIcon(icon) {
				this.selectValue = icon
				this.visible = false
				this.$emit('onChange', icon)
			}
		}
	}
</script>

<style lang="less" scoped>
	.icon-list {
		display: flex;
		flex-wrap: wrap;
		list-style: none;

		.icon-item {
			margin: 0 3px 2px 0;
			padding: 5px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-items: center;
			border: 1px solid #ccc;

			&:hover {
				background-color: var(--el-color-primary);
				color: #fff;
				border-color: #fff;

			}

			i {
				&:hover {
					// color: var(--el-color-primary);
					border-color: var(--el-color-primary);
					transition: all 0.2s;
					transform: scaleX(1.1);
				}
			}
		}
	}
</style>